# -*- coding:utf-8 -*-
import requests
import json
import re
import base64
import binascii
import rsa
#import sys
#sys.setdefaultencoding('utf-8')

def prelogin():
    url = 'http://login.sina.com.cn/sso/prelogin.php'
    nick = '13817993337'
    payload = {
                'entry':  'weibo',
                'callback': 'sinaSSOController.preloginCallBack',
                'su': '13817993337',
                'rsakt': 'mod',
                'client': 'ssologin.js(v1.4.18)',
                '_': 1424184775928 
                }

    r = requests.get(url, params=payload)
    return r

def prepare_login_info(prelogin_text):
    start = prelogin_text.find('(')
    end = prelogin_text.find(')')
    prelogin_text = prelogin_text[start+1:end]
    prelogin_json = json.loads(prelogin_text)
    #print prelogin_json
    #print prelogin_json['rsakv']
    return prelogin_json

def login():
    r = prelogin()
    prelogin_info = prepare_login_info(r.text)

    servertime = prelogin_info['servertime']
    rsakv = prelogin_info['rsakv'] 
    nonce = prelogin_info['nonce'] 
    su = base64.b64encode('13817993337') 
    rsaPublickey = int(prelogin_info['pubkey'],16)
    key = rsa.PublicKey(rsaPublickey, 655537)
    pwd = 'shao2013'
    message = str(servertime) +'\t' + str(nonce) + '\n' + str(pwd)
    sp = binascii.b2a_hex(rsa.encrypt(message,key))

    url = 'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)'
    payload = {
            'entry':     'weibo',
            'gateway':    1,
            'from'   :      '', 
            'savestate':    0,
            'useticket':    1,
            'pagerefer':    '', 
            'vsnf'     :      1,
            'su'       :      su,
            'service'  :      'miniblog',
            'servertime':   servertime,
            'nonce'     :   'D84NWH',
            'pwencode'  :    'rsa2',
            'rsakv':    rsakv,
            'sp':       sp,
            'sr':  1680*1050,
            'encoding'  :  'UTF-8',
            'prelt'     :  350,
            'url'       :  'http%3A%2F%2Fweibo.com%2Fajaxlogin.php%3Fframelogin%3D1%26callback%3Dparent.sinaSSOController.feedBackUrlCallBack',
            'returntype' :  'META'
            } 

    data = '%s\n' % json.dumps(payload)
    headers = { 
                'Host':         'login.sina.com.cn',
                'Connection':   'keep-alive',
                'Content-Length': len(data)
               } 
    r = requests.post(url, data=data, headers=headers)
    return r

r = login()
url = re.findall("location.replace\(\"(.+?)\"\);", r.text)[0]
r = requests.get(url)
with open('login.txt', 'w') as f:
    f.write(r.text.encode('utf-8'))

url = "http://weibo.com/u/1782707647/"
r = requests.get(url) 
with open('home.txt', 'w') as f:
    f.write(r.text.encode('utf-8'))
